package com.rh.controller;

import com.rh.Enums;
import com.rh.dto.Message;
import com.rh.dto.Result;
import com.rh.excrptions.DoException;
import com.rh.service.EmployeeService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@CrossOrigin
@Controller
@ResponseBody
public class UserController {
    @Autowired
    private EmployeeService employeeService;
    /**
     * 注册
     */
    @RequestMapping(value = "/userRegisters",method = RequestMethod.POST)
    public Result userRegisters(String email,String empPassword) {
        try {
                //生成盐
                String salt = email;
                //加密
                String source=empPassword;
                Md5Hash md5Hash = new Md5Hash(source, salt, 1024);
                String newPassword = md5Hash.toHex();
                employeeService.register(email,newPassword,salt);
                Result result = new Result();
                return result;
        }catch (Exception e){
            e.printStackTrace();
            throw new DoException(Enums.REGISTER_ERROR);
        }
    }
    /**
     * 登陆
     */

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public Result userLogin(String email,String empPassword){
          try {
              System.out.println("邮箱：" + email + "密码：" + empPassword);
              //获取Shiro实体
              Subject sb = SecurityUtils.getSubject();
              UsernamePasswordToken token = new UsernamePasswordToken(email, empPassword);
              //进行验证
              Result result = new Result();
              sb.login(token);
              return result;
          }catch (Exception e){
              throw new DoException(Enums.LOGIN_ERROR);
          }
          }

    @RequestMapping("/toLogin")
    public Result toLogin(){
        Message message = new Message();
        message.setMsg("请登录！！");
        message.setCode(208);
        Result result = new Result();
        result.setMessage(message);
        return result;
    }

    @RequestMapping("/unauthorized")
    public Result unauthorized(){
        Message message = new Message();
        message.setCode(207);
        message.setMsg("未授权！");
        Result result = new Result();
        result.setMessage(message);
        return result;
    }
}
